package com.smartleanx.module.hrm.service.esign.service.impl;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.smartleanx.framework.common.pojo.PageResult;
import com.smartleanx.framework.datapermission.core.annotation.DataPermission;
import com.smartleanx.framework.security.core.util.SecurityFrameworkUtils;
import com.smartleanx.module.hrm.dal.dataobject.employee.EmployeeDO;
import com.smartleanx.module.hrm.dal.dataobject.esign.ElecCorp;
import com.smartleanx.module.hrm.dal.mysql.esign.ElecCorpMapper;
import com.smartleanx.module.hrm.dal.mysql.esign.HrmEContractTaskMapper;
import com.smartleanx.module.hrm.service.employee.EmployeeService;
import com.smartleanx.module.hrm.service.esign.eums.ActorTypeEnum;
import com.smartleanx.module.hrm.service.esign.eums.TaskStatusEnum;
import com.smartleanx.module.hrm.service.esign.service.HrmEContractTaskActorsService;
import com.smartleanx.module.hrm.service.esign.service.HrmEContractTaskService;
import com.smartleanx.module.hrm.service.esign.service.HrmEContractTempActorsService;
import com.smartleanx.module.hrm.service.esign.temp.param.HrmEContractTaskParam;
import com.smartleanx.module.hrm.service.esign.temp.po.HrmEContractTask;
import com.smartleanx.module.hrm.service.esign.temp.po.HrmEContractTaskActors;
import com.smartleanx.module.hrm.service.esign.temp.result.HrmETaskListResult;
import com.smartleanx.module.system.api.user.AdminUserApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * e签宝合同签署Service实现
 *
 * @author xzq
 * @since 2025-07-07 16:04:49
 */
@Service
public class HrmEContractTaskServiceImpl extends ServiceImpl<HrmEContractTaskMapper, HrmEContractTask> implements HrmEContractTaskService {

    @Autowired
    private HrmEContractTaskMapper hrmEContractTaskMapper;
    @Autowired
    private HrmEContractTaskActorsService hrmEContractTaskActorsService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private AdminUserApi adminUserApi;
    @Autowired
    private ElecCorpMapper elecCorpMapper;

    @Override
    public PageResult<HrmETaskListResult> getTaskPage(HrmEContractTaskParam param) {
//        List<Long> taskIds = new ArrayList<>();
//        if(StrUtil.isNotBlank(param.getActor())){
//            List<HrmEContractTaskActors> taskActorList = hrmEContractTaskActorsService.getTaskActorListByActorName(param.getActor());
//            taskIds = taskActorList.stream().map(HrmEContractTaskActors::getTaskId).collect(Collectors.toList());
//        }
        Integer count = hrmEContractTaskMapper.getTaskCountSql(param);
        PageHelper.startPage(param.getPageNo(), param.getPageSize());
        List<HrmETaskListResult> taskList = hrmEContractTaskMapper.getTaskPageSql(param);
        List<Long> taskIds = taskList.stream().map(HrmETaskListResult::getId).collect(Collectors.toList());
        List<HrmEContractTaskActors> taskActorList = hrmEContractTaskActorsService.getTaskActorListByTaskId(taskIds);
        Map<Long, List<HrmEContractTaskActors>> actorMap = taskActorList.stream().collect(Collectors.groupingBy(HrmEContractTaskActors::getTaskId));

        taskList.stream().peek(p ->{
            List<HrmEContractTaskActors> taskActors = actorMap.get(p.getId());
            int corpCurrent = 0;
            int personCurrent = 0;
            //1. 创建中
            if(p.getTaskStatus() == TaskStatusEnum.CREATE_ING.getCode()){
                corpCurrent = 1;
            }
            //2.待查看
            if(p.getTaskStatus() == TaskStatusEnum.AWAIT_VIEW.getCode()){
                for (HrmEContractTaskActors taskActor : taskActors) {
                    if(taskActor.getActorType().equals(ActorTypeEnum.CORP.getCode())){
                        p.setActorName(taskActor.getActorName());
                        if(taskActor.getReadStatus() == 0){
                            corpCurrent = 1;
                            break;
                        }
                    }
                    if(taskActor.getActorType().equals(ActorTypeEnum.PERSON.getCode())){
                        if(taskActor.getReadStatus() == 0){
                            personCurrent = 1;
                            break;
                        }
                    }
                }
            }
            //3. 待填写(企业)
            if(p.getTaskStatus() == TaskStatusEnum.AWAIT_FILL_IN_CORP.getCode()){
                corpCurrent = 1;
            }

            //4. 待填写(员工)
            if(p.getTaskStatus() == TaskStatusEnum.AWAIT_FILL_IN_PERSON.getCode()){
                personCurrent = 1;
            }
            //5. 填写完成  不做处理

            //6. 待签署(企业)
            if(p.getTaskStatus() == TaskStatusEnum.AWAIT_SIGN_CORP.getCode()){
                corpCurrent = 1;
            }

            //7. 待签署(员工)
            if(p.getTaskStatus() == TaskStatusEnum.AWAIT_SIGN_PERSON.getCode()){
                personCurrent = 1;
            }

            //8.参与人
            List<HrmETaskListResult.Actor> actors = new ArrayList<>();
            for (HrmEContractTaskActors taskActor : taskActors) {
                HrmETaskListResult.Actor actor = new HrmETaskListResult.Actor();
                actor.setActorName(taskActor.getActorName());
                if(taskActor.getActorType().equals(ActorTypeEnum.CORP.getCode())){
                    ElecCorp elecCorp = elecCorpMapper.selectById(p.getCorpId());
                    actor.setActorName(elecCorp.getCorpName());
                    actor.setCurrent(corpCurrent);
                }
                if(taskActor.getActorType().equals(ActorTypeEnum.PERSON.getCode())){
                    actor.setCurrent(personCurrent);
                }
                actors.add(actor);
            }

            p.setActorList(actors);

            //9. 时间节点
            HrmETaskListResult.EffectiveDuration effectiveDuration = new HrmETaskListResult.EffectiveDuration();
            effectiveDuration.setFlag(0);
            if(p.getEndTime() != null){
                if(DateUtil.compare(p.getEndTime(),new Date()) > 1 && DateUtil.compare(DateUtil.offsetDay(p.getCreateTime(),-3),new Date()) > 1){
                    effectiveDuration.setFlag(1);
                }
                effectiveDuration.setTime(DateUtil.format(p.getEndTime(),DatePattern.NORM_DATETIME_PATTERN));
                p.setEffectiveDuration(effectiveDuration);
            }else{
                if(p.getTaskStatus() > TaskStatusEnum.FILL_IN_ACC.getCode()){
                    effectiveDuration.setTime("长期有效");
                    p.setEffectiveDuration(effectiveDuration);
                }else{
                    effectiveDuration.setTime("");
                    p.setEffectiveDuration(effectiveDuration);
                }
            }


            //10. 开始/结束时间
            ArrayList<String> timeList = new ArrayList<>();
            timeList.add(DateUtil.format(p.getCreateTime(),DatePattern.NORM_DATETIME_PATTERN));
            if(StrUtil.isNotBlank(p.getProcessEndTime())){
                timeList.add(p.getProcessEndTime());

            }
            p.setTimeList(timeList);

        }).collect(Collectors.toList());



        return new PageResult<>(taskList,count.longValue());
    }

    @Override
    @DataPermission(enable = false)
    public PageResult<HrmETaskListResult> getTaskAppPage(HrmEContractTaskParam param) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        EmployeeDO employee = employeeService.getEmployeeByUserId(userId);
        param.setEmpId(employee.getId());
        Integer count = hrmEContractTaskMapper.getTaskCountSqlApp(param);
        PageHelper.startPage(param.getPageNo(), param.getPageSize());
        List<HrmETaskListResult> taskList = hrmEContractTaskMapper.getTaskPageSqlApp(param);
        List<Long> taskIds = taskList.stream().map(HrmETaskListResult::getId).collect(Collectors.toList());
        List<HrmEContractTaskActors> taskActorList = hrmEContractTaskActorsService.getTaskActorListByTaskId(taskIds);
        Map<Long, List<HrmEContractTaskActors>> actorMap = taskActorList.stream().collect(Collectors.groupingBy(HrmEContractTaskActors::getTaskId));

        taskList.stream().peek(p ->{
            List<HrmEContractTaskActors> taskActors = actorMap.get(p.getId());
            int corpCurrent = 0;
            int personCurrent = 0;
            //1. 创建中
            if(p.getTaskStatus() == TaskStatusEnum.CREATE_ING.getCode()){
                corpCurrent = 1;
            }
            //2.待查看
            if(p.getTaskStatus() == TaskStatusEnum.AWAIT_VIEW.getCode()){
                for (HrmEContractTaskActors taskActor : taskActors) {
                    if(taskActor.getActorType().equals(ActorTypeEnum.CORP.getCode())){
                        if(taskActor.getReadStatus() == 0){
                            corpCurrent = 1;
                            break;
                        }
                    }
                    if(taskActor.getActorType().equals(ActorTypeEnum.PERSON.getCode())){
                        if(taskActor.getReadStatus() == 0){
                            personCurrent = 1;
                            break;
                        }
                    }
                }
            }
            //3. 待填写(企业)
            if(p.getTaskStatus() == TaskStatusEnum.AWAIT_FILL_IN_CORP.getCode()){
                corpCurrent = 1;
            }

            //4. 待填写(员工)
            if(p.getTaskStatus() == TaskStatusEnum.AWAIT_FILL_IN_PERSON.getCode()){
                personCurrent = 1;
            }
            //5. 填写完成  不做处理

            //6. 待签署(企业)
            if(p.getTaskStatus() == TaskStatusEnum.AWAIT_SIGN_CORP.getCode()){
                corpCurrent = 1;
            }

            //7. 待签署(员工)
            if(p.getTaskStatus() == TaskStatusEnum.AWAIT_SIGN_PERSON.getCode()){
                personCurrent = 1;
            }

            //8.参与人
            List<HrmETaskListResult.Actor> actors = new ArrayList<>();
            for (HrmEContractTaskActors taskActor : taskActors) {
                HrmETaskListResult.Actor actor = new HrmETaskListResult.Actor();
                actor.setActorName(taskActor.getActorName());
                if(taskActor.getActorType().equals(ActorTypeEnum.CORP.getCode())){
                    ElecCorp elecCorp = elecCorpMapper.selectById(p.getCorpId());
                    actor.setActorName(elecCorp.getCorpName());
                    p.setActorName(taskActor.getActorName());
                    actor.setCurrent(corpCurrent);
                }
                if(taskActor.getActorType().equals(ActorTypeEnum.PERSON.getCode())){
                    p.setActorFillInTime(taskActor.getActorFillInTime());
                    actor.setCurrent(personCurrent);
                }
                actors.add(actor);
            }

            p.setActorList(actors);

            //9. 时间节点
            HrmETaskListResult.EffectiveDuration effectiveDuration = new HrmETaskListResult.EffectiveDuration();
            effectiveDuration.setFlag(0);
            if(p.getEndTime() != null){
                if(DateUtil.compare(p.getEndTime(),new Date()) > 1 && DateUtil.compare(DateUtil.offsetDay(p.getCreateTime(),-3),new Date()) > 1){
                    effectiveDuration.setFlag(1);
                }
                effectiveDuration.setTime(DateUtil.format(p.getEndTime(),DatePattern.NORM_DATETIME_PATTERN));
                p.setEffectiveDuration(effectiveDuration);
            }else{
                effectiveDuration.setTime("长期有效");
                p.setEffectiveDuration(effectiveDuration);
            }


            //10. 开始/结束时间
            ArrayList<String> timeList = new ArrayList<>();
            timeList.add(DateUtil.format(p.getCreateTime(),DatePattern.NORM_DATETIME_PATTERN));
            timeList.add(DateUtil.format(p.getEndTime(),DatePattern.NORM_DATETIME_PATTERN));
            p.setTimeList(timeList);

            p.setTime(DateUtil.format(p.getCreateTime(),DatePattern.NORM_DATETIME_PATTERN));

        }).collect(Collectors.toList());


        return new PageResult<>(taskList,count.longValue());
    }

    @Override
    public HrmEContractTask getTaskByProcessId(String processId) {
        return getOne(new LambdaQueryWrapper<HrmEContractTask>()
        .eq(HrmEContractTask::getDataStatus,1)
        .eq(HrmEContractTask::getBpmProcessId,processId));
    }
}
